import React from 'react';
import './index.less';
import proFetch from 'src/hrpub/common/utils/project-fetch';
import downLoad from "src/hrpub/common/utils/download/download.js";
import TrnsTypeRef from "../../../../../refer/hiref/TrnsTypeGridRef/index.js";
import PsnJobRef from "src/hrhi/refer/hiref/PsnjobRefTreeGridRef";
import {base,toast,formDownload} from 'nc-lightapp-front';
import PropTypes from 'prop-types';
const propTypes = {
    MultiInit: PropTypes.object,
    modalClose: PropTypes.func,
    showModal:PropTypes.boolean,
    exportEmptyParams:PropTypes.object,
    importDefaultParams:PropTypes.object,
    urlParams:PropTypes.object
};
/* 
urlParams = {
    import:'/nccloud/hrhi/archive/ArchiveImportAction.do',
    export:'/nccloud/hrhi/archive/ArchiveExportAction.do'
}
*/ 
const {NCModal,NCSelect,NCButton,NCFormControl} = base;
const {NCOption} = NCSelect;
class HrImport extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            language:{}, //多语
            fileName: '', //上传的文件name
            file:null,
            uploadResult: '',
            errorMessage: '',
            uploadSuccess: '', //上传成功
            trnsType:{}, //业务类型
            psnJob:"", //人员
            oriPsnJob:[],
            transFunc:'',
            transFuncList:[] //调配方式
        };

        this.fileChange = this.fileChange.bind(this);
        this.importFile = this.importFile.bind(this);
        this.errexport = this.errexport.bind(this);
        this.kbImpTemp = this.kbImpTemp.bind(this);
        this.closeModal = this.closeModal.bind(this);

    }
    componentDidMount() {
        this.getLanguage();
    }
    TrnsTypeChange=(value)=>{
        console.log('调配类型',value)
        this.setState({
            trnsType:value
        })
    }
    psnJobChange=(value)=>{
        console.log('调配人员',value)
        let result = [];
        value.map((item)=>{
            result.push(item.values['hi_psnjob.pk_psnjob'].value)
        })
        let strRes =""
        if(value.length > 1){
            strRes = result.join(',')
        }else if(value.length === 1){
            strRes = result[0]
        }
        this.setState({
            oriPsnJob:value,
            psnJob:strRes
        })
    }
    selectChange = (value)=>{
        console.log('调配方式',value)
        this.setState({
            transFunc:value
        })
    }
    getLanguage() {
        this.props.MultiInit.getMultiLang({
            domainName: 'hrpub',
            moduleId: 'hrpub',
            callback: (json, status, init) => {
                this.setState({
                    language: json,
                    transFuncList:[
                        {
                            key:'1',
                            label:json['hrpub-000179'] || '组织内调动'
                        },
                        {
                            key:'2',
                            label:json['hrpub-000180'] || '跨组织调出'
                        },
                        // {
                        //     key:'3',
                        //     label:json['hrpub-000181'] || '跨组织调入'
                        // }
                    ] //调配方式
                });
            }
        });
    }

    // 选择文件触发事件
    fileChange = (e) => {
        let file = e.target.files[0]
        let fileName = file.name
        this.setState({
            file:file,
            fileName
        })
    }
    // 点击导入按钮执行函数
    importFile = async () => {
        const {file,language, trnsType, transFunc} = this.state
        console.log(file)
        if (!file) {
            toast({
                color: 'warning',
                content:language['hrpub-000182'] || '请先选择excel文件！'// 请先选择excel文件！
            })
            return false
        }
        if(Object.keys(trnsType).length === 0){
            toast({
                color: 'warning',
                content:'请填写调配类型' 
            })
            return false
        }

        let uploadResult = language['hrpub-000183'] // 上传失败！
        let errorMessage = ''
        let uploadSuccess = true
        let formData = new FormData();
        let data = {}
        let dataSucce = ''
        formData.append('file',file)
        data = {
            pk_org:this.props.org.refpk,
            trnsType: trnsType.refpk,
            transFunc: transFunc
        }
        dataSucce = JSON.stringify(data)
        formData.append('busiParamJson1', dataSucce)
        try {
            await proFetch({
                url:this.props.urlParams.import,
                // '/nccloud/hrhi/archive/ArchiveImportAction.do',
                body:formData,
                headers:{'Content-Type': 'multipart/form-data'}
            }).then((res)=>{
                if (res.success) {
                    document.querySelector('#fileIpt').value = ''
                    // console.log(document.querySelector('#fileIpt','document.querySelector'))
                    if(res.data.status === '200' || res.data.isSuccess === 'Y') {
                        uploadResult = language['hrpub-000184'] // 上传成功！
                        // this.c.action.ma.getTableData();
                        toast({
                            color: 'success',
                            content:language['hrpub-000184'] || '上传成功'// 请先选择excel文件！
                        })
                        this.closeModal()
    
                    } else {
                        uploadSuccess = false
                        errorMessage = res.data.message || res.data.errorMessage
                        this.errexport(res)
                        this.setState({
                                uploadResult,
                                errorMessage,
                                uploadSuccess
                            }
                        );
                    }
                } 
            },(err)=>{
                uploadSuccess = false
                this.setState(
                    {
                        uploadSuccess
                    }
                );
            })
        } catch(err){
            uploadSuccess = false
            this.setState(
                {
                    uploadSuccess
                },
            );
        }
    }
    errexport = (res) => {
        let data = {}
        let info = {
            fileName:res.data.fileName,
            downLoadFlag:'Y'
        }
        data = {
            busiParamJson1:JSON.stringify(info),
        }
        formDownload({
            url: this.props.urlParams.import,
            // '/nccloud/hrbm/bmfile/ImportAction.do',
            params: data,
            enctype: 2,
        })
    }
    //导出
    kbImpTemp = (param = {}) => {
        const {trnsType,psnJob,transFunc,language} = this.state
        if(JSON.stringify(param) === '{}' ){
            param = {   pk_org:this.props.org.refpk,
                        trnsType:trnsType.refpk, 
                        psnjobpks:psnJob, 
                        transFunc,
                    }
            }
            return () => {
                if(!transFunc || Object.keys(trnsType).length === 0){
                    toast({
                        color: 'warning',
                        content:language['hrpub-000185'] || '请填写调配类型和调配方式' //请填写调配类型和调配方式
                    })
                    return false
                }
                let info = {
                    ...param
                }
                console.log(info)
                let data = {
                    busiParamJson:JSON.stringify(info),
                }
                // formDownload({
                //     params: {
                //         jsonStr: JSON.stringify({
                //             pk_org: this.props.orgVal.refpk,
                //             sheetNames: this.state.targetKeys.join(),
                //             funCode: '60070employee_ncc'
                //         })
                //     },
                //     url: this.props.urlParams.export,
                //     enctype: 2,
                // });
                formDownload({
                    url:this.props.urlParams.export,
                    //  '/nccloud/hrhi/archive/ArchiveExportAction.do',
                    params: data,
                    enctype: 2,
                })
            }
    }
    //关闭弹窗的前编
    closeModal(){
        this.setState({
            fileName: '',
            file: null,
            uploadResult: '',
            errorMessage: ''
        },()=>{
            this.props.modalClose()
        })
    }
    render() {
        const {
            language,
            fileName, //上传的文件name
            uploadResult,
            errorMessage,
            uploadSuccess, //上传成功
            trnsType,
            psnJob,
            oriPsnJob,
            transFunc,
            transFuncList
        } = this.state;
        const {
            showModal,
            org
        } = this.props
        return (
            <div className="import">
            <NCModal 
                  show = {showModal}
                  onHide = {this.closeModal}
              >
                <NCModal.Header  closeButton={true}>
                  {/* 导入 */}
                  <NCModal.Title>{language['hrpub-000175']}</NCModal.Title>
                </NCModal.Header>
                <NCModal.Body>
                <div className="importBlock">
                        <div className="ibLeft"></div>
                        <div className="ibRight">
                            <div className="ibrConSelect">
                            <div className="import-transFunc">
                            <span className = 'require'>*</span>{language['hrpub-000186'] || '调配类型：'}
                                <TrnsTypeRef
                                    onChange={this.TrnsTypeChange}
                                    queryCondition={() => {
                                        return {
                                            'trnsEvent':'3'
                                        }
                                    }}
                                    value={trnsType}
                                />
                            </div>
                            <div className="import-transFunc mar-lf5">
                                {language['hrpub-000187'] || '调配人员：'}
                                <PsnJobRef
                                    onChange={this.psnJobChange}
                                    queryCondition={() => {
                                        return {
                                            "pk_org": org.refpk,//主组织
                                            "istran": true, // true:在职  false:离职
                                            "isIncludeKeyPsnGrp": true,// true:在职  false:离职
                                            "GridRefActionExt": "nccloud.web.hrtrn.pub.sqlbuilder.PsntransterAddPsnRefSqlBuilder"
                                        }
                                    }}
                                    value={oriPsnJob}
                                    isMultiSelectedEnabled={true}
                                />
                            </div>
                            <div className="import-transFunc">
                            <span className = 'require'>*</span>{language['hrpub-000188'] || '调配方式：'}
                                <NCSelect 
                                    placeholder = {language['hrpub-000189'] || '调配方式'}
                                    value={transFunc}
                                    // disabled = {bc.editStatus !== 'browse'}
                                    onChange={this.selectChange}
                                >
                                    {transFuncList.map((item) => {
                                        return (
                                            <NCOption value={item.key}>
                                                {item.label}
                                            </NCOption>
                                        )
                                    })}
                                </NCSelect>
                            </div>
                            </div>
                        </div>
                        <div className="blockLine"></div>
                    </div>
                    <div className="importBlock">
                        <div className="ibLeft"></div>
                        <div className="ibRight">
                            <div className="ibrCon">
                                {/* 模板下载 */}
                                <a className="ibrFir" onClick={this.kbImpTemp()}>{language['hrpub-000190'] || '模板下载'}</a>
                                {/* 第一次导入前请下载模版，并按照文件格式要求填充数据 */}
                                <span className="ibrSec">{language['hrpub-000191'] || '第一次导入前请下载模版，并按照文件格式要求填充数据'}</span>
                            </div>
                        </div>
                        <div className="blockLine"></div>
                    </div>
                    <div className="importBlock">
                        <div className="ibLeft"></div>
                        <div className="ibRight">
                            <div className="ibrConSec">
                                {/* 数据文件 */}
                                <span className="ibrsFir">{language['hrpub-000192'] || '数据文件'}</span>
                                {/* 点击按钮选择数据文件，点击导入上传该文件 */}
                                <span className="ibrsSec">{language['hrpub-000193'] || '点击按钮选择数据文件，点击导入上传该文件'}</span>
                            </div>
                            <div className="ibrConTh">
                                <div className="filname">{fileName}</div>
                                {/* 选择文件 */}
                                <div className="selectFileBtn">{language['hrpub-000194'] || '选择文件'}</div>
                                <input id="fileIpt" className="fileIpt" onChange={this.fileChange} type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
                                {/* 导入 */}
                                <div className="importBtn" onClick={this.importFile}>{language['hrpub-000195']|| '导入'}</div>
                            </div>
                        </div>
                        <div className="blockLine"></div>
                    </div>
                    <div className="importBlock">
                        <div className="ibLeft"></div>
                        <div className="ibRight">
                            <div className="uploadCon">
                                {/* 上传结果 */}
                                <span className="resultTitle">{language['hrpub-000196'] || '上传结果'}</span>
                                <span className="uploadResult" style={{color: uploadSuccess ? 'green' : 'red'}}>{uploadResult}</span>
                            </div>
                            <div className="errorMessage">{errorMessage}</div>
                        </div>
                    </div>
                </NCModal.Body>
                <NCModal.Footer>
                </NCModal.Footer>

              </NCModal>
        </div>
        )
    }
}
HrImport.propTypes = propTypes;
export default HrImport;